python 获取内存和cpu的使用率 您所在的位置:网站首页 ios cpu占用率 python 获取内存和cpu的使用率

python 获取内存和cpu的使用率

2023-10-06 02:03| 来源: 网络整理| 查看: 265

在这里插入图片描述

获取远端设备的内存使用率和CPU使用率

Python前辈封装了一个Paramiko模块,允许我们通过SSH对远程系统进行操作,上传和下载文件非常方便。他的使用很直观,下面是使用Paramiko封装的一个获取cpu、内存使用率的一个例子;

import paramiko import time linux = ['192.168.11.111'] def connectHost(ip, uname='root', passwd='bjzh@2020#7120'): ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(ip, username=uname, password=passwd, port=2020) return ssh def MainCheck(): try: while True: for a in range(len(linux)): ssh = connectHost(linux[a]) # 查询主机名称 cmd = 'hostname' stdin, stdout, stderr = ssh.exec_command(cmd) host_name = stdout.readlines() host_name = host_name[0] # 查看当前时间 csj = 'date +%T' stdin, stdout, stderr = ssh.exec_command(csj) curr_time = stdout.readlines() curr_time = curr_time[0] # 查看cpu使用率(取三次平均值) cpu = "vmstat 1 3|sed '1d'|sed '1d'|awk '{print $15}'" stdin, stdout, stderr = ssh.exec_command(cpu) cpu = stdout.readlines() cpu_usage = str(round((100 - (int(cpu[0]) + int(cpu[1]) + int(cpu[2])) / 3), 2)) + '%' # 查看内存使用率 mem = "cat /proc/meminfo|sed -n '1,4p'|awk '{print $2}'" stdin, stdout, stderr = ssh.exec_command(mem) mem = stdout.readlines() mem_total = round(int(mem[0]) / 1024) mem_total_free = round(int(mem[1]) / 1024) + round(int(mem[2]) / 1024) + round(int(mem[3]) / 1024) mem_usage = str(round(((mem_total - mem_total_free) / mem_total) * 100, 2)) + "%" print(host_name, curr_time, cpu_usage, mem_usage) time.sleep(10) except: print("连接服务器 %s 异常" % (linux[a])) if __name__ == '__main__': MainCheck() 获取本机CPU温度、使用率、内存使用率、硬盘使用率等

在Python中获取系统信息的另一个好办法是使用psutil这个第三方模块。顾名思义,psutil = process and system utilities,它不仅可以通过一两行代码实现系统监控,还可以跨平台使用,支持Linux/UNIX/OSX/Windows等,是系统管理员和运维小伙伴不可或缺的必备模块。

获取CPU信息 import psutil psutil.cpu_count() # CPU逻辑数量 psutil.cpu_count(logical=False) # CPU物理核心 CPU使用率,每秒刷新一次 print(psutil.cpu_percent(interval=1, percpu=True)) 获取内存信息

使用psutil获取物理内存和交换内存信息,分别使用:

psutil.virtual_memory() psutil.virtual_memory().percent #获取内存使用率 psutil.swap_memory() 获取磁盘信息

可以通过psutil获取磁盘分区、磁盘使用率和磁盘IO信息:

psutil.disk_partitions() # 磁盘分区信息 psutil.disk_usage('/') # 磁盘使用情况 psutil.disk_io_counters() # 磁盘IO

在这里插入图片描述



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有